const express = require('express');
const ejs = require('ejs-mate');
const layout = require('express-layout');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const config = require('./config.js');
const api = require('./api/api.js');
const router = require('./routes/router');
const session = require('express-session');
const redis = require('redis');
const redisStore = require('connect-redis')(session);
const errorPageMiddlewares = require('./middleware/error');
const path = require('path');
const app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
app.engine('html',ejs);
app.use(layout());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser('',{httpOnly:false}));
const redisClient = redis.createClient({
    host: config.redisHost,
    port: config.redisPort
});
app.use(session({
    store:new redisStore({
        client: redisClient
    }),
    secret: 'qianneizhu',
    resave:false,
    saveUninitialized:false,
    cookie: {
        maxAge:1000*60*60*24
    }
}));

app.use('/public',express.static(path.join(__dirname, 'public')));
app.locals.config = config;
app.use('/',api);
app.use('/',router);

app.use(errorPageMiddlewares.errorPage);
app.use('/*',function(req,res){
    if(!res.headersSent){
        res.render404();
    }
});


module.exports = app;
